<?php

namespace app\mobile\controller;

use app\common\model\CardCzgive;
use app\common\model\CardCzLog;
use app\common\model\CardFansNoticeLog;
use app\common\model\CardGeneral;
use app\common\model\CardGivecardLog;
use app\common\model\CardGoods;
use app\common\model\CardMember;
use app\common\model\CardOrder;
use app\common\model\CardStore;
use app\common\model\CardUserGet;
use app\common\model\CardRank;
use app\common\model\Agent;
use app\common\model\CardUserUpdate;
use app\common\model\MerchantContent;
use app\common\model\Momerchant;
use app\common\model\OpenTemplate;
use app\common\model\Paylog;
use app\common\model\WxOpen;
use app\common\model\Merchant;
use app\common\model\System;
use app\common\validate\LoginUsers;
use think\Controller;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;

class Cardusernu extends Mobiletest
{

    //我的卡券  查询所有属于该openid的会员卡
    /*
     * $card_id
     */
    public function mecard()
    {
        $arr = request()->param();
        $this->_init();
        if (isset($arr['card_id'])) {
            $appid = $this->getappid($arr['card_id']);
            $card_id = $arr['card_id'];
        } else {
            $appid = $this->getappidmid($arr['mid']);
            $card_id = $this->get_cardid_mid($arr['mid']);
        }
        $openid = Session::get($appid . '_openid');
//        $CardMember = new CardMember();
        //我的会员卡
        $CardUserGet = new CardUserGet();
        //我的券
        $maps['openid'] = $openid;
        $maps['have'] = 1;
        $maps['card_type'] = array('neq', 'MEMBER_CARD');
        $maps['statu'] = ['neq', 2];
        $mevou = $CardUserGet->where($maps)->order('statu asc')->select();
//        var_dump($CardUserGet->getLastSql());
        $this->assign('mevou', $mevou);
        $this->assign('card',$arr);
       return $this->fetch();
    }


    //待领取的卡券
    //未领取到的卡券
    public function getcardlistnu()
    {
//        try {
            $arr = request()->param();
            $this->_init();
            $Merchant = new Merchant();
            $CardGeneral = new CardGeneral();
            if (isset($arr['card_id'])) {
                $appid = $this->getappid($arr['card_id']);
                $user['top_mid'] = $CardGeneral->where(['card_id'=>$arr['card_id']])->value('top_mid');
            } else {
                $appid = $this->getappidmid($arr['mid']);
                $user['top_mid'] = $Merchant->where(['id'=>$arr['mid']])->value('top_mid');
            }
            $openid = Session::get($appid . '_openid');
            $user['openid'] = $openid;
            $this->assign('card', $arr);
            $this->assign('user', $user);
            return $this->fetch();
//        } catch (\Exception $e) {
//            echo "系统繁忙，请稍后再试！！！";
//        }
    }


    //待领取的卡券列表
    public function getcardslistsrnu()
    {
        $arr = request()->param();
//        return json($arr);
        $CardGivecardLog = new CardGivecardLog();
        $map['top_mid'] = $arr['top_mid'];
        $map['openid'] = $arr['openid'];
        $cardlist = $CardGivecardLog->where($map)->order('id desc')->paginate(5);
        $cardcount = $CardGivecardLog->where($map)->count('id');
//        return json($cardlist);
        $page_num = ceil($cardcount / 5);
        if ($cardlist) {
            if ($page_num > (int)$arr['page'] || $page_num == (int)$arr['page']) {
                $cardlists = [];
                $i = 0;
                foreach ($cardlist as $k => $v) {
                    $cards = filegetcard($v['zs_card_id'], $v['openid']);
                    if ($v['put_sume'] > $v['get_sume'] && $cards['result'] == 1) {
                        $cardlists[$i] = $v;
                        $cardlists[$i]['card_title'] = $cards['cards']['title'];
                        $cardlists[$i]['card_logo'] = $cards['cards']['logo_url'];
                        $cardlists[$i]['brand_name'] = $cards['cards']['brand_name'];
                        $cardlists[$i]['card_type'] = getcardtype($cards['cards']['card_type']);
                        $i = $i + 1;
                    }
                }
                if ($cardlists) {
                    $data['code'] = 0;
                    $data['message'] = 'SUCCESS';
                    $data['data']['data'] = $cardlists;
                    $data['count'] = $cardcount;
                    $data['page_num'] = $page_num;
                    $data['page'] = $arr['page'];
                } else {
                    $data['code'] = 0;
                    $data['data']['data'] = '';
                    $data['message'] = 'error';
                    $data['count'] = 0;
                    $data['page_num'] = 0;
                    $data['page'] = $arr['page'];
                }
            } else {
                $data['code'] = 9002;
                $data['data']['data'] = '';
                $data['message'] = 'error';
                $data['page_num'] = 0;
                $data['count'] = 0;
                $data['page'] = $arr['page'];
            }
        } else {
            $data['code'] = 9002;
            $data['data']['data'] = '';
            $data['message'] = 'error';
            $data['page_num'] = $page_num;
            $data['count'] = $cardcount;
            $data['page'] = $arr['page'];
        }
        return json($data);
    }


    //领取卡券
    public function getcardslistnu()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
            $Merchant = new Merchant();
            $top_mid = $Merchant->where('id', $arr['mid'])->value('top_mid');
            $sinfo = $Merchant->where('id', $arr['mid'])->value('wx_open_id');
            $WxOpen = new WxOpen();
            $sappid = $WxOpen->where('id', $sinfo)->value('authorizer_appid');
            $logopenid = $arr['openid'];
            $openid = Session::get($sappid . '_openid');
            //判断领卡人是否正确]
            if ($logopenid == $openid) {
                $CardGivecardLog = new CardGivecardLog();
                $cardlist = $CardGivecardLog->where(['mid' => $arr['mid'], 'openid' => $openid])->select();
                $card = [];
                foreach ($cardlist as $k => $v) {
                    $outer_str = 'giveRecId_' . $v['id'];
                    $isgetput = $this->isgetputsume($v['zs_card_id'], $outer_str, $openid, $v['put_sume']);
                    if ($v['put_sume'] > $v['get_sume'] && $isgetput == 0) {
                        for ($x = 0; $x < $v['put_sume']; $x++) {
                            $options = $this->options($v['zs_card_id']);
                            $arrs['card_id'] = $v['zs_card_id'];
                            $arrs['openid'] = $openid;
                            $arrs['outer_str'] = 'giveRecId_' . $v['id'];
                            $card[] = $this->putlist($arrs);
                        }
                    }
                }
                if (isset($options)) {
                    $weObj = new Wxobjopen($options);
                    $url = $arr['url'];
                    $jssdk = $weObj->getJsSign($url);
                    $data['code'] = 0;
                    $data['message'] = 'success';
                    $data['data']['jssdk'] = $jssdk;
                    $data['data']['card'] = $card;
                } else {
                    $data['code'] = 9001;
                    $data['message'] = '您已领取完成';
                }
            } else {
                $data['code'] = 9003;
                $data['message'] = '领卡信息有误';
            }
            return json($data);
        }
    }




    //p
    public function getcardlist(){
        $arr = request()->param();
        $this->_init();
        $CardFansNoticeLog = new CardFansNoticeLog();
        $map['id'] = $arr['rec_id'];
        $user = $CardFansNoticeLog->where($map)->find();
        if ($user) {
            $this->assign('card',$arr);
            $this->assign('user',$user);
            return $this->fetch();
        }else{
            return $this->fetch('off');
        }
    }

    //待领取的卡券
    public function getcardslists()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();

//            $user['get_time'] = $arr['create_time'];
//            $this->checkfirecards($user);
            $CardGivecardLog = new CardGivecardLog();
            $idlist = explode(',',$arr['getlist']);


            $map['id'] = ['in',$idlist];

            $cardlist = $CardGivecardLog->where($map)->order('id desc')->select();
         
            if ($cardlist) {
                $CardGel = new CardGeneral();
                $cardlists = [];
                $i= 0;
                foreach ($cardlist as $k => $v) {
                    if ($v['put_sume'] > $v['get_sume'] && getcardgetsume($v['zs_card_id']) > getcardgetuser($v['zs_card_id'],$v['openid']) && fileoffcards($v['zs_card_id'])) {
                        $cardlists[$i] = $v;
                        $cards = $CardGel->where(['card_id'=>$v['zs_card_id']])->field('title,logo_url,brand_name,card_type')->find();
                        $cardlists[$i]['card_title'] = $cards['title'];
                        $cardlists[$i]['card_logo'] = $cards['logo_url'];
                        $cardlists[$i]['brand_name'] = $cards['brand_name'];
                        $cardlists[$i]['card_type'] = getcardtype($cards['card_type']);
                        $i = $i+1;
                    }
                }
//                $cardlists = $cardlist;
                if ($cardlists){
                    $data['code'] = 0;
                    $data['message'] = 'SUCCESS';
                    $data['data'] = $cardlists;
                    $data['count'] = count($cardlists);
                    $data['page'] = '';
                }else{
                    $data['code'] = 9001;
                    $data['message'] = 'error';
                }
            }else{
                $data['code'] = 9001;
                $data['message'] = 'error';
            }
            return json($data);
        }
    }


    //关闭页面 (jssdk 实现)
    /*
     * $card_id
     *
     */
    public function weboff($card_id)
    {
        //jssdk
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $options = $this->options($card_id);
        $weObj = new Wxobjopen($options);
        $jssdk = $weObj->getJsSign($url);
        $this->assign('jssdk', $jssdk);
        return $this->fetch();
    }

    //打开卡
    /*
     * $card_id /
     *
     */
    public function opencard()
    {
        $this->_init();

        $card_id = request()->param('card_id');
        $appid = $this->getappid($card_id);
        $openid = Session::get($appid.'_openid');
        $CradUserGet = new CardUserGet();
        $info = $CradUserGet->where(['card_id' => $card_id, 'openid' => $openid, 'have' => '1', 'statu' => 0])->find();
        if ($info) {
            $card['card_id'] = $card_id;
            $card['code'] = $info['code'];
            $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

            $options = $this->options($card_id);
            $weObj = new Wxobjopen($options);
            $jssdk = $weObj->getJsSign($url);
            //输出内容
            $card['jssdk']['debug'] = true;
            $card['jssdk']['appId'] = $jssdk['appId'];
//                $card['jssdk']['api_ticket'] = $jssdk['ticket'];
//            var_dump($url);
//                $card['jssdk']['url'] = $jssdk['url'];
            $card['jssdk']['timestamp'] = $jssdk['timestamp'];
            $card['jssdk']['nonceStr'] = $jssdk['nonceStr'];
            $card['jssdk']['signature'] = $jssdk['signature'];
            $card['jssdk']['jsApiList'] = ['hideAllNonBaseMenuItem','openCard'];
            $card['card']['cardId'] = $card_id;
            $card['card']['code'] = $info['code'];
            $this->assign('jssdk', $jssdk);
            $this->assign('card', $card);
            return $this->fetch();
        } else {
            $data['card_id'] = $card_id;
            $data['openid'] = $openid;
            $this->redirect(url('carduser/addcard', $data));
        }
    }

    //发放卡
    /*
     * $arr['openid'] / $arr['card_id']
     *
     *
     */
    public function addcard()
    {
//        $this->_init();
        $arr = request()->param();
        if (isset($arr['openid']) && isset($arr['card_id'])) {
            $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $options = $this->options($arr['card_id']);
            //发放
            $arrs['card_id'] = $arr['card_id'];
            $arrs['openid'] = $arr['openid'];
            $weObj = new Wxobjopen($options);
            $card = $this->put($arrs);
            $jssdk = $weObj->get_card_JsSign($url);
            $jssdk['url'] = $url;
            $this->assign('card', $card);
            $this->assign('jssdk', $jssdk);
            return $this->fetch();
        }
    }

    //发放卡
    /*
     *
     *
     */
    public function addcardmicro()
    {
        $this->_init();

        $card_id = request()->param('card_id');
        $appid = $this->getappid($card_id);
        $openid = Session::get($appid.'_openid');
        if (isset($openid) && isset($card_id)) {
            $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $options = $this->options($card_id);
            //发放
            $arrs['card_id'] = $card_id;
            $arrs['openid'] = $openid;
            $weObj = new Wxobjopen($options);
            $card = $this->put($arrs);
            $jssdk = $weObj->get_card_JsSign($url);
            $jssdk['url'] = $url;
            $this->assign('card', $card);
            $this->assign('jssdk', $jssdk);
            return $this->fetch();
        }
    }


    //AJax打开卡
    /*
     * $arr['card_id'] , $arr['url']
     *
     */
    public function getopencard(){
        if (Request()->isAjax()){
            $arr = request()->post();
            $card_id = $arr['card_id'];
            $appid = $this->getappid($card_id);
            $openid = Session::get($appid.'_openid');
            $CradUserGet = new CardUserGet();
            $map['openid'] = $openid;
            $map['card_id'] = $card_id;
            $map['have'] = 1;
            $map['statu'] = 0;
            $info = $CradUserGet->where(['card_id' => $card_id, 'openid' => $openid, 'have' => '1', 'statu' => 0])->find();
            if ($info) {
                $url = $arr['url'];
                $options = $this->options($card_id);
                $weObj = new Wxobjopen($options);

                $jssdk = $weObj->getJsSign($url);
                //输出内容
                $card['jssdk']['debug'] = true;
                $card['jssdk']['appId'] = $jssdk['appId'];
//                $card['jssdk']['api_ticket'] = $jssdk['ticket'];
//                $card['jssdk']['url'] = $jssdk['url'];
                $card['jssdk']['timestamp'] = $jssdk['timestamp'];
                $card['jssdk']['nonceStr'] = $jssdk['nonceStr'];
                $card['jssdk']['signature'] = $jssdk['signature'];
                $card['jssdk']['jsApiList'] = ['hideAllNonBaseMenuItem','openCard'];
                $card['card']['cardId'] = $card_id;
                $card['card']['code'] = $info['code'];
                return json($card);
            } else {
                $data['code'] =  9001;
                $data['msg'] = '没有此卡，请先领取！';
                return json($data);
            }
        }
    }

    //Ajax打开领取
    /*
     * $arr['card_id']
     */
    public function getaddcard(){
        if (Request()->isAjax()){
            $arr = request()->post();
            $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $options = $this->options($arr['card_id']);
            //发放
            $arrs['card_id'] = $arr['card_id'];
            $appid = $this->getappid($arr['card_id']);
            $arrs['openid'] = Session::get($appid.'_openid');
            $weObj = new Wxobjopen($options);
            $jssdk = $weObj->get_card_JsSign($url);
            //输出内容
            $card['card'] = $this->put($arrs);
            $card['jssdk']['debug'] = false;
            $card['jssdk']['api_ticket'] = $jssdk['ticket'];
            $card['jssdk']['url'] = $jssdk['url'];
            $card['jssdk']['appId'] = $jssdk['appId'];
            $card['jssdk']['timestamp'] = $jssdk['timestamp'];
            $card['jssdk']['nonceStr'] = $jssdk['nonceStr'];
            $card['jssdk']['signature'] = $jssdk['signature'];
            $card['jssdk']['jsApiList'] = ['penCard','addCard'];
            return json($card);
        }
    }

    //发放卡列表
    /*
     * $arr['openid'] / $arr['give'] /
     *
     */
    public function addcardlist()
    {
        $this->_init();
        $arr = request()->param();
        if (isset($arr['openid']) && isset($arr['give'])) {
            $appid = $this->getappid($arr['card_id']);
            if ($arr['openid'] == Session::get($appid.'_openid')) {
                $CardCzgive = new CardCzgive();
                $card_id = $CardCzgive->where('id', $arr['give'])->value('zs_card_id');
                $cardlist = explode(',', $card_id);
                $card = [];
                foreach ($cardlist as $k => $v) {
                    if (filteroffcard($v) == true) {
                        $options = $this->options($v);
                        $arrs['card_id'] = $v;
                        $arrs['openid'] = $arr['openid'];
                        $card[$k] = $this->putlist($arrs);
                    }
                }
                if(isset($options)){
                    $weObj = new Wxobjopen($options);
                    $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                    $jssdk = $weObj->getJsSign($url);
                    $this->assign('card', json_encode($card));
                    $this->assign('jssdk', $jssdk);
                    return $this->fetch();
                }
                else{
                    $this->error("该卡券已过期");
                }
            }else{
                $CardCzgive = new CardCzgive();
                $card_id = $CardCzgive->where('id', $arr['give'])->value('card_id');
                $this->redirect('Carduser/weboff', ['card_id' => $card_id]);
            }
        }
    }

    //批量投放
    /*
     * $arr['openid'] / $arr['card_id']
     */
    private function putlist($arr){
        $options = $this->options($arr['card_id']);
        $weObj = new Wxobjopen($options);
        $noncestr = $weObj->generateNonceStr();
        $res['cardId'] = $arr['card_id'];
        $res['cardExt'] = $weObj->wxAddCard($arr['openid'], $arr['card_id'], $noncestr);
        return $res;
    }

    //投放卡
    /*
     * $arr['openid'] / $arr['card_id']
     */
    private function put($arr)
    {
        $options = $this->options($arr['card_id']);
        $weObj = new Wxobjopen($options);
        $noncestr = $weObj->generateNonceStr();
        $outer_str = 'CardCenter';
        $res['card_id'] = $arr['card_id'];
        $res['addcard'] = $weObj->wxAddCard($arr['openid'], $arr['card_id'], $noncestr,$outer_str);
        return $res;

    }

    //获取该门店所属商户的所有下属门店
    /*
     * $mid
     */
    private function getmidlist($mid){
        $Merchant = new Merchant();
        $top_mid = $Merchant->where('id',$mid)->value('top_mid');
        $midlist = $Merchant->where(['top_mid' => $top_mid])->field('id')->select();
        $smid=[];
        foreach ($midlist as $k => $v) {
            $smid[] = $v['id'];
        }
        $mids = implode(',', $smid);
        return $mids;
    }

    /* 获取创建该卡券的门店id
     *
     * $card_id
     *
     */
//    private function getmid($card_id)
//    {
//        $CardMember = new CardMember();
//        $CardGeneral = new CardGeneral();
//        $top_mid = $CardMember->where(['card_id' => $card_id])->value('mid');
//        if (empty($top_mid)) {
//            $top_mid = $CardGeneral->where(['card_id' => $card_id])->value('mid');
//            return $top_mid;
//        } else {
//            return $top_mid;
//        }
//    }



    //分享jssdk
    /*
     * $card_id
     * 
     */
    private function getsharejssdk($arr){
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $options = $this->options($arr);
        //分享
        $weObj = new Wxobjopen($options);
        $jssdk = $weObj->getJsSign($url);
        $wxJsSdk = [
            'debug' => false,
            'appId' => $jssdk['appId'],
            'timestamp' =>$jssdk['timestamp'],
            'nonceStr' => $jssdk['nonceStr'],
            'signature' => $jssdk['signature'],
            'jsApiList' => [
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareQZone',
                'closeWindow',
                'hideAllNonBaseMenuItem',
            ]
        ];
        return $wxJsSdk;
    }
    public function test(){
        echo request()->domain();
        exit();
        $s=getgivecardnew('[{"zs_card_id":"pCVCLv0Z2UNmnrRcoC2bamHpj0EY","zs_no":"2"}]',0);
   var_dump($s);
    }


}
